package async;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author fei.fang
 * @date 2021/8/26
 **/
public class ReadWriteLockTest{

    private static Lock lock = new ReentrantLock();

    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static Lock readLock = readWriteLock.readLock();

    private static Lock writeLock = readWriteLock.writeLock();

    int value;

    public Object handlerRead(Lock lock) throws InterruptedException{
        try{
            lock.lock();

            Thread.sleep(1000);
            return value;
        }finally{
            System.out.println("read - " + System.currentTimeMillis());
            lock.unlock();
        }
    }

    public void handlerWrite(Lock lock,int index) throws InterruptedException{
        try{
            lock.lock();

            Thread.sleep(1000);
            value = index;
        }finally{
            System.out.println("write - " + System.currentTimeMillis());
            lock.unlock();
        }
    }

    public static void main(String[] args){
        final ReadWriteLockTest test = new ReadWriteLockTest();
        Runnable readRun = new Runnable(){

            @Override public void run(){
                try{
                    test.handlerRead(readLock);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        };

        Runnable writeRun = new Runnable(){

            @Override public void run(){
                try{
                    test.handlerWrite(writeLock,new Random().nextInt());
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        };

        long start = System.currentTimeMillis();
        System.out.println(start);
        for (int i =0; i<18; i++){
            new Thread(readRun).start();
        }
        for (int i =0; i<18; i++){
            new Thread(writeRun).start();
        }
        long end = System.currentTimeMillis();
        System.out.println(end);
        System.out.println((end - start)/1000);
    }
}
